'use strict';
const db = uniCloud.database();

exports.main = async (event, context) => {
  const { deviceId } = event;

  if (!deviceId) {
    return {
      code: -1,
      message: '设备ID不能为空'
    };
  }

  try {
    // 先检查设备是否存在
    const device = await db.collection('devices')
      .doc(deviceId)
      .get();

    if (!device.data || device.data.length === 0) {
      return {
        code: -1,
        message: '设备不存在'
      };
    }

    // 删除设备
    const result = await db.collection('devices')
      .doc(deviceId)
      .remove();

    console.log('删除设备结果:', result);

    if (result.deleted === 1) {
      return {
        code: 0,
        message: '删除成功'
      };
    } else {
      return {
        code: -1,
        message: '删除失败'
      };
    }
  } catch (e) {
    console.error('删除设备失败:', e);
    return {
      code: -1,
      message: '删除设备失败',
      error: e.message
    };
  }
}; 